package util

import (
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
)

var (
	dbPath string = "./resource/ip2region.xdb"
	cBuff []byte
)

func init() {
	var err error
	cBuff, err = xdb.LoadContentFromFile(dbPath)
	if err != nil {
		fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
		return
	}
}

type Location struct {
	Country string `json:"country"`
	Province string `json:"province"`
	City string	`json:"city"`
}

func GetRealIP(c *gin.Context) string {
	return c.Request.Header.Get("X-Forward-For")
}


func GetLocationByContext(c *gin.Context) (Location, error) {
	location := Location{
		Country: "",
		City: "",
	}

    searcher, err := xdb.NewWithBuffer(cBuff)
    if err != nil {
        fmt.Printf("failed to create searcher: %s\n", err.Error())
        return location, err
    }

    defer searcher.Close()

	ipString := GetRealIP(c)

	if ipString == "::1" {
		ipString = "127.0.0.1"
	}

    region, err := searcher.SearchByStr(ipString)
    if err != nil {
        fmt.Printf("failed to SearchIP(%s): %s\n", ipString, err)
        return location, err
    }
	regions := strings.Split(region, "|")
	location.Country = regions[0]
	location.Province = regions[2]
	location.City = regions[3]

	return location, nil
}

